import React from 'react';
// 导入NavBar组件
import { Toast } from 'antd-mobile'
import { List, AutoSizer } from 'react-virtualized'
import axios from 'axios';
import NavHeader from '../../components/NavHeader'
import './index.scss'

// 导入utils中的获取当前城市的方法
import { getCurrentCity } from '../../utils/index'


// 导入CSSModules的样式文件
import styles from './index.module.css'
console.log(styles)

// 标题索引的高度
const TITLE_HEIGHT = 36
const NAME_HEIGHT = 50

// 封装处理字母索引的方法
const formatCityIndex = (letter) => {
  switch (letter) {
    case '#':
      return '当前定位'
    case 'hot':
      return '热门城市'
    default:
      return letter.toUpperCase()
  }
}

// 对接收到的list处理，返回处理好的cityList和cityIndex
const formatCityData = (list) => {
  const cityList = {}
  // 索引的数组，主要是首字母
  let cityIndex = []
  list.forEach(item => {
    // 获取首字母
    const first = item.short.substr(0, 1)
    // 如果有该索引
    if (cityList[first]) {
      cityList[first].push(item)
    } else {
      cityList[first] = [item]
    }
  })
  cityIndex = Object.keys(cityList).sort()
  return {
    cityList,
    cityIndex
  }
}

const HOUSE_CITY = ['北京', '上海', '广州', '深圳']

export default class CityList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      cityList: {},
      cityIndex: [],
      activeIndex: 2, // 指定右侧索引高亮的符号
    }

    // 创建Ref对象
    this.cityListComponent = React.createRef()
  }

  // 获取列表数据
  async getCityList() {
    const res = await axios.get('http://103.153.138.54:8080/area/city?level=1')
    const { cityList, cityIndex } = formatCityData(res.data.body)

    // 获取热门城市数据
    const hotRes = await (await axios.get('http://103.153.138.54:8080/area/hot')).data.body
    cityIndex.splice(0, 0, 'hot')
    cityList['hot'] = hotRes

    // 获取当前城市数据
    const curCity = await getCurrentCity()
    cityList['#'] = [curCity]
    cityIndex.splice(0, 0, '#')
    // console.log(cityList, cityIndex)
    this.setState({
      cityList,
      cityIndex
    })
  }
  async componentDidMount() {
    await this.getCityList()

    // 提前计算好List中每一项对应高度，实现精确跳转
    this.cityListComponent.current.measureAllRows()
  }

  // 创建动态计算每一行高度的方法
  getRowHeight = ({ index }) => {
    // return 100
    // 返回高度计算公式：标题高度（固定一行） + 城市列表高度（固定一行 * 城市数目）
    const { cityIndex, cityList } = this.state
    // console.log(cityIndex, cityList)
    return TITLE_HEIGHT + NAME_HEIGHT * cityList[cityIndex[index]].length
  }

  // 改选城市
  changeCity({ label, value }) {
    if (HOUSE_CITY.indexOf(label) > -1) {
      // 若当前城市有信息
      console.log(label)
      localStorage.setItem('hkzf_city', JSON.stringify({ label, value }))
      this.props.history.go(-1)
    } else {
      Toast.info('该城市暂无房源数据', 1, null, false);
    }
  }

  // 渲染每一行数据的函数
  rowRenderer = ({
    key, // Unique key within array of rows
    index, // 索引
    isScrolling, // The List is currently being scrolled
    isVisible, // 这行是否在list中可见
    style, // 指定每一行的位置，必须加上
  }) => {
    // 获取每一行的字符索引
    console.log(this.state)
    const { cityIndex, cityList } = this.state
    const letter = cityIndex[index]
    // console.log(cityList[letter])
    return (
      <div key={key} style={style} className="city">
        <div className="title">{formatCityIndex(letter)}</div>
        {
          cityList[letter].map(item => <div className="name" key={item.value} onClick={() => this.changeCity(item)}>{item.label}</div>)
        }
      </div>
    )
  }

  // 右侧索引列表
  renderCityIndex() {
    const { cityIndex, activeIndex } = this.state
    // console.log(cityIndex)
    return cityIndex.map((item, index) =>
      <li className="city-index-item" key={item} onClick={() => { this.cityListComponent.current.scrollToRow(index) }}>
        <span className={activeIndex === index ? 'index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
      </li>
    )
  }

  // 获取List组件渲染行信息
  onRowsRendered = ({ startIndex }) => {
    if (this.state.activeIndex !== startIndex) {
      this.setState({
        activeIndex: startIndex
      })
    }
  }
  render() {
    return (
      <div className='cityList'>
        {/* 头部导航 */}
        <NavHeader name="城市选择" />

        {/* 城市列表 */}
        <AutoSizer>
          {({ width, height }) => (
            <List
              ref={this.cityListComponent}
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.getRowHeight}               //设定每一行的高度
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              scrollToAlignment="start"
            />
          )}
        </AutoSizer>

        {/* 右侧索引列表 */}
        <ul className="city-index">
          {this.renderCityIndex()}
        </ul>

        {/* <div className={styles.test}>测试样式覆盖问题</div> */}
      </div>
    )
  }
}